<?php
/**
 * @author			JiangYegen
 * @package 		Functions类
 * @copyright		Copyright (c) 2013-04-4,
 *
 *------------------------------------------------------------------
 *在工程所有文件中均不需要单独初始化这个类，可直接用 $func 进行操作
 *自定义功能扩展函数
 *------------------------------------------------------------------
 */
$fun = new FUNCTIONS();

class FUNCTIONS {

		//识别换行与空格
		public function htmlcode($string,$bIsHtml=false)
		{
			if (!$bIsHtml)
			{
				$string=htmlspecialchars($string);
			}
			$string=str_replace(' ','&nbsp;',$string);
			$string=str_replace("\t",'&nbsp;&nbsp;&nbsp;&nbsp;',$string);
			$string=nl2br($string);
			return $string;
		}


		/* * *****************************************
		 函 数 名: getAge()
		函数功能: 输入1990-01-24获取年龄
		* ***************************************** */

		//获取年龄
		public function getAge($birthday) {
			$age = 0;
			$year = $month = $day = 0;
			if (is_array($birthday)) {
				extract($birthday);
			} else {
				if (strpos($birthday, '-') !== false) {
					list($year, $month, $day) = explode('-', $birthday);
					$day = substr($day, 0, 2); //get the first two chars in case of '2000-11-03 12:12:00'
				}
			}
			$age = date('Y') - $year;
			if (date('m') < $month || (date('m') == $month && date('d') < $day)) $age--;
			return $age;
		}



		//操作提示信息
		public function msg($msgs,$url,$s=1,$title="系统提示",$back_color="66B1DD",$link_url="")
		{
			@$str="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
			$str .="<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>".$title."</title>";
			$str .="<link href='{$link_url}favicon.ico' type='image/x-icon' rel='icon' />";
			$str .="<link href='{$link_url}favicon.ico' type='image/x-icon' rel='shortcut icon'/></head>";
			$str .="<body>";
			$str .= "<center>";
			$str .= "  <div id=\"msg\" style=\"font-size:18px;width:500px; padding:15px; border: 10px solid #{$back_color}; background-color: #FFF; margin:150px auto;\">\n";
			$str .= "  <div style=\"margin:30px auto;text-align:center;font-size:18px;font-weight:bold; color:#666;\"><img src=\"{$link_url}images/loading.gif\">$msgs</div>\n";
			if(is_numeric($url)){
				$str .= '    <script language="javascript" type="text/javascript">setTimeout("history.go(-1)",'.($s*1000).');</script>';
				$str .= "    <p style=\"text-align:center;\"><a style=\"font-size:14px;color:#333;font-weight:bold; text-decoration:underline;\" href=\"javascript:history.go(-1);\">如果您的浏览器没有自动跳转,请点击这里...</a></p>\n";
			}
			else if(empty($url)){
			$str .= '    <script language="javascript" type="text/javascript">setTimeout("history.go(-1)",'.($s*1000).');</script>';
			$str .= "    <p style=\"text-align:center;\"><a style=\"font-size:14px;color:#333;font-weight:bold; text-decoration:underline;\" href=\"javascript:history.go(-1);\">如果您的浏览器没有自动跳转,请点击这里...</a></p>\n";
			}
			else{
				$str .= "    <meta http-equiv=\"refresh\" content=\"$s;url=$url\">\n";
				$str .= "    <p style=\"text-align:center;\"><a style=\"font-size:14px;color:#333;font-weight:bold; text-decoration:underline;\" href=\"$url\">如果您的浏览器没有自动跳转,请点击这里...</a></p>\n";
			}
			$str .= "  </div>\n";
			$str .= "</center>";
			exit($str."</body>\n</html>");
		}

		/**
		 * 字符串截取指定长度
		 * 例如$db->cut_str($str,8,0,'GBK');//前面显示八个字符
		 * @return string
		 */
		public  function cut_str($string,$sublen,$start=0,$code='UTF-8')
		{
				if($code=='UTF-8')
				{
					$pa="/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/";
					preg_match_all($pa,$string,$t_string);

					if(count($t_string[0])-$start>$sublen) return join('',array_slice($t_string[0],$start,$sublen))."...";
					return join('',array_slice($t_string[0],$start,$sublen));
				}
				else
				{
					$start=$start*2;
					$sublen=$sublen*2;
					$strlen=strlen($string);
					$tmpstr='';

					for($i=0;$i<$strlen;$i++)
					{
					if($i>=$start&&$i<($start+$sublen))
					{
					if(ord(substr($string,$i,1))>129)
					{
					$tmpstr.=substr($string,$i,2);
					}
					else
					{
					$tmpstr.=substr($string,$i,1);
					}
					}
					if(ord(substr($string,$i,1))>129) $i++;
					}
					if(strlen($tmpstr)<$strlen ) $tmpstr.="";
					return $tmpstr;
				}
			}


			/**
			* 获取每个汉字拼音首字母
			* @return $ret
			*/
			//比较汉字ASC码
			public function getfirstchar($s0){
			$fchar = ord($s0{0});
			if($fchar >= ord("A") and $fchar <= ord("z") )
				return strtoupper($s0{0});
				@$s1 = iconv("UTF-8","GBK", $s0);
				@$s2 = iconv("GBK","UTF-8", $s1);
			if($s2 == $s0){
				$s = $s1;
			}else{
				$s = $s0;
			}
			$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
			if($asc>=-20319 and $asc<=-20284)return "A";
			elseif($asc>=-20283 and $asc<=-19776)return "B";
			elseif($asc>=-19775 and $asc<=-19219)return "C";
			elseif($asc>=-19218 and $asc<=-18711)return "D";
			elseif($asc>=-18710 and $asc<=-18527)return "E";
			elseif($asc>=-18526 and $asc<=-18240)return "F";
			elseif($asc>=-18239 and $asc<=-17923)return "G";
			elseif($asc>=-17922 and $asc<=-17418)return "H";
			elseif($asc>=-17417 and $asc<=-16475)return "J";
			elseif($asc>=-16474 and $asc<=-16213)return "K";
			elseif($asc>=-16212 and $asc<=-15641)return "L";
			elseif($asc>=-15640 and $asc<=-15166)return "M";
			elseif($asc>=-15165 and $asc<=-14923)return "N";
			elseif($asc>=-14922 and $asc<=-14915)return "O";
			elseif($asc>=-14914 and $asc<=-14631)return "P";
			elseif($asc>=-14630 and $asc<=-14150)return "Q";
			elseif($asc>=-14149 and $asc<=-14091)return "R";
			elseif($asc>=-14090 and $asc<=-13319)return "S";
			elseif($asc>=-13318 and $asc<=-12839)return "T";
			elseif($asc>=-12838 and $asc<=-12557)return "W";
			elseif($asc>=-12556 and $asc<=-11848)return "X";
			elseif($asc>=-11847 and $asc<=-11056)return "Y";
			elseif($asc>=-11055 and $asc<=-10247)return "Z";
			else return null;
		}
		//调用给出返回值
		public function top_pinyin($zh,$top=0){
				@$ret = "";
				@$s1 = iconv("UTF-8","GBK", $zh);
				@$s2 = iconv("GBK","UTF-8", $s1);
				if($s2 == $zh){
				$zh = $s1;
				}
				if($top==0){
					$j=strlen($zh);
				}else{
					$j=2;
				}
				for($i = 0; $i < $j; $i++){
				$s1 = substr($zh,$i,1);
				$p = ord($s1);
					if($p > 160){
					$s2 = substr($zh,$i++,2);
					$ret .= $this->getfirstchar($s2);
					}else{
					$ret .= $s1;
				}
			}
			return $ret;
		}

		/**
		 * 将汉字全部转换为拼音
		 * 只能识别国标码中的一级汉字，3000多个，生僻字不行
		 * $fun->pinyin("江业根","1");
		 * //第二个参数: "1"为utf8编码  "2"为gbk编码
		 **/
		public  function pinyin($_String, $_Code='1'){ //GBK页面可改为2，1为UTF8

			$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".
					"|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".
					"cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".
					"|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".
					"|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".
					"|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".
					"|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".
					"|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".
					"|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".
					"|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".
					"|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".
					"she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".
					"tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".
					"|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".
					"|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".
					"zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
			$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".
					"|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".
					"|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".
					"|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".
					"|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".
					"|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".
					"|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".
					"|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".
					"|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".
					"|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".
					"|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".
					"|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".
					"|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".
					"|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".
					"|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".
					"|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".
					"|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".
					"|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".
					"|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".
					"|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".
					"|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".
					"|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".
					"|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".
					"|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".
					"|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".
					"|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".
					"|-10270|-10262|-10260|-10256|-10254";
			$_TDataKey   = explode('|', $_DataKey);
			$_TDataValue = explode('|', $_DataValue);
			$_Data = array_combine($_TDataKey, $_TDataValue);
			arsort($_Data);
			reset($_Data);
			if($_Code!= "2") $_String = $this->_U2_Utf8_Gb($_String);
			$_Res = '';
			for($i=0; $i<strlen($_String); $i++) {
				$_P = ord(substr($_String, $i, 1));
				if($_P>160) {
					$_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536;
				}
				$_Res .= $this->_Pinyin($_P, $_Data);
			}
			return preg_replace("/[^a-z0-9]*/", '', $_Res);
		}
		  private  function _Pinyin($_Num, $_Data){
			if($_Num>0 && $_Num<160 ){
				return chr($_Num);
			}elseif($_Num<-20319 || $_Num>-10247){
				return '';
			}else{
				foreach($_Data as $k=>$v){ if($v<=$_Num) break; }
				return $k;
			}
		}
		  private  function _U2_Utf8_Gb($_C){
			$_String = '';
			if($_C < 0x80){
				$_String .= $_C;
			}elseif($_C < 0x800) {
				$_String .= chr(0xC0 | $_C>>6);
				$_String .= chr(0x80 | $_C & 0x3F);
			}elseif($_C < 0x10000){
				$_String .= chr(0xE0 | $_C>>12);
				$_String .= chr(0x80 | $_C>>6 & 0x3F);
				$_String .= chr(0x80 | $_C & 0x3F);
			}elseif($_C < 0x200000) {
				$_String .= chr(0xF0 | $_C>>18);
				$_String .= chr(0x80 | $_C>>12 & 0x3F);
				$_String .= chr(0x80 | $_C>>6 & 0x3F);
				$_String .= chr(0x80 | $_C & 0x3F);
			}
			return @iconv('UTF-8', 'GB2312', $_String);
		}

		//获得当前的脚本网址 $code=0不显示参数 $code=1显示参数 $code=2只是获取参数
		public function GetCurUrl($code=0)
		{
			$pageURL = 'http';

			if (@$_SERVER["HTTPS"] == "on")
			{
				$pageURL .= "s";
			}
			$pageURL .= "://";

			$this_page = $_SERVER["REQUEST_URI"];

			if(empty($code)){
				// 只取 ? 前面的内容
				if (strpos($this_page, "?") !== false)
				@$this_page = reset(explode("?", $this_page));
			}elseif($code==2){
				if (strpos($this_page, "?") !== false)
				@$this_page = explode("?", $this_page);
				return  @$pageURL=next($this_page);
				exit();//结束 返回参数
			}else{}

			if ($_SERVER["SERVER_PORT"] != "80")
			{
				$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $this_page;
			}
			else
			{
				$pageURL .= $_SERVER["SERVER_NAME"] . $this_page;
			}
			return $pageURL;
		}

		//设置分页uri
		public function setPageUri($p='page'){
		    $url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?");
		    $parse = parse_url($url);
		    if(isset($parse['query'])) {
		        parse_str($parse['query'],$params);
		        unset($params[$p]);
		        $url   =  $parse['path'].'?'.http_build_query($params);
		    }
		    return $url;
		}

		/**
		* 获取服务器IP地址
		*/
		public function get_web_ip() {
					if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
						$ip = @$_SERVER["HTTP_X_FORWARDED_FOR"];
					else if (@$_SERVER["HTTP_CLIENT_IP"])
						$ip = @$_SERVER["HTTP_CLIENT_IP"];
								else if (@$_SERVER["REMOTE_ADDR"])
	 				$ip = @$_SERVER["REMOTE_ADDR"];
	 			else if (getenv("HTTP_X_FORWARDED_FOR"))
	 				$ip = getenv("HTTP_X_FORWARDED_FOR");
		 						else if (getenv("HTTP_CLIENT_IP"))
		 						$ip = getenv("HTTP_CLIENT_IP");
	 			else if (getenv("REMOTE_ADDR"))
	 				$ip = getenv("REMOTE_ADDR");
		 				else
	 				$ip = "Unknown";
		 				return $ip;
					}

		/* * *****************************************
		 函 数 名: get_day_time()
		函数功能: 获取两个时间相差多少天 时 分 秒 这里是获取天数
		* ***************************************** */
		public function get_day_time($val){

			if(!empty($val)){
				$seconds = $val%60;
				$val = (int)($val/60);
				$minutes = $val%60;
				$val = (int)($val/60);
				$hours = $val%24;
				$days = (int)($val/24);

				/*
				$hoursValue=($hours<10)?"0".$hours:$hours;

				$minutesValue=($minutes<10)?"0".$minutes:$minutes;

				$secondsValue=($seconds<10)?"0".$seconds:$seconds;
				*/

				return $newtime=$days;/*.$hoursValue.":".$minutesValue.":".$secondsValue;*/

			}else{
				return $val;
			}

		}

		//判断两个数组是否相等
		public function judgeEqual($key1,$key2){
		    if(array_diff($key1,$key2) || array_diff($key2,$key1)){
			        return true;//不等
			    }else{
			        return false;//相等
				    }
				}

		//防注入安全获得
		public function safeRequest($str){
			$str = trim($str);
			$str = strip_tags($str);
			$str = htmlspecialchars($str);
			//$rstr = array(' ','>','<','!','$','#','&','@','%','^','*','(',')','-','+','|','}','{',']','[','/',"'",'\\','?',',');
			$rstr = array(' ','>','<','!','$','#','&','^','(',')',"'",'\\');
			$str = str_replace($rstr,array(''),$str);

			return $str;
			}

/*********************************************************************
	函数名称:encrypt
	函数作用:加密解密字符串
 	使用方法:
		加密     :encrypt('str','E','nowamagic');
		解密     :encrypt('被加密过的字符串','D','nowamagic');
		案例	  :
		$id = "123";
	    $mykey="hedgehog";//加密密钥
	    $token = encrypt($id, 'E', $mykey);
	    echo '加密:'.encrypt($id, 'E', $mykey);
	    echo '<br />';
	    echo '解密：'.encrypt($token, 'D', $mykey);
		参数说明:
		$string   :需要加密解密的字符串
		$operation:判断是加密还是解密:E:加密   D:解密
		$key      :加密的钥匙(密匙);
*********************************************************************/
    public function encrypt($string,$operation,$key='')
    {
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
         for($i=0;$i<=255;$i++)
        {
        	$rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++)
        {
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++)
        {
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }

        if($operation=='D')
        {
         if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8))
            {
                return substr($result,8);
            }
            else
            {
                return'';
            }
        }
        else
        {
            return str_replace('=','',base64_encode($result));
        }
    }

	/**
	   * @param string $string 原文或者密文
	   * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
	   * @param string $key 密钥
	   * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
	   * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
	   *
	   * @example
	   *
	   *  $a = authcode('abc', 'ENCODE', 'key');
	   *  $b = authcode($a, 'DECODE', 'key');  // $b(abc)
	   *
	   *  $a = authcode('abc', 'ENCODE', 'key', 3600);
	   *  $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
	   */
 		public function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {

         $ckey_length = 6;
         // 随机密钥长度 取值 0-32;
         // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
         // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
         // 当此值为 0 时，则不产生随机密钥

         $key = md5($key ? $key : 'default_key'); //这里可以填写默认key值
         $keya = md5(substr($key, 0, 16));
         $keyb = md5(substr($key, 16, 16));
         $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

         $cryptkey = $keya.md5($keya.$keyc);
         $key_length = strlen($cryptkey);

         $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
         $string_length = strlen($string);

         $result = '';
         $box = range(0, 255);

         $rndkey = array();
         for($i = 0; $i <= 255; $i++) {
             $rndkey[$i] = ord($cryptkey[$i % $key_length]);
         }

         for($j = $i = 0; $i < 256; $i++) {
             $j = ($j + $box[$i] + $rndkey[$i]) % 256;
             $tmp = $box[$i];
             $box[$i] = $box[$j];
             $box[$j] = $tmp;
         }

         for($a = $j = $i = 0; $i < $string_length; $i++) {
             $a = ($a + 1) % 256;
             $j = ($j + $box[$a]) % 256;
             $tmp = $box[$a];
             $box[$a] = $box[$j];
             $box[$j] = $tmp;
             $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
         }

         if($operation == 'DECODE') {
             if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                 return substr($result, 26);
             } else {
                 return '';
             }
         } else {
             return $keyc.str_replace('=', '', base64_encode($result));
         }

     }
     //输入安全过滤 预防数据库攻击
     public function checkInput($value)
     {
     	// 去除斜杠
     	if (get_magic_quotes_gpc())
     	{
     		$value = stripslashes($value);
     	}
     	//如果不是数字则转义
     	if (!is_numeric($value))
     	{
     		$value = mysql_real_escape_string($value);
     	}
     	return $value;
     }
     //显示到页面 防止js运行
     public function showInput($value,$ent=ENT_QUOTES,$charset="UTF-8")
     {
     	$value=isset($value)?htmlentities($value, $ent,$charset):"";
     	// 去除斜杠
     	if (get_magic_quotes_gpc())
     	{
     		$value = stripslashes($value);
     	}
     	$value=isset($value)?str_replace("\\","",$value):"";
     	return $value;
     }
		/**
		 * 获取客户端操作系统
 		 */
		public function get_OS(){
			$os = false;
				@$strAgent=$_SERVER['HTTP_USER_AGENT'];
				if(@eregi('win',$strAgent) && strpos($strAgent,'95')){
					$os = 'Windows 95';
				} else if(@eregi('win 9x',$strAgent) && strpos($strAgent,'4.90')){
					$os = 'Windows ME';
				} else if(@eregi('win',$strAgent) && @eregi('98',$strAgent)){
					$os = 'Windows 98';
				} else if(@eregi('win',$strAgent) && @eregi('nt 6.2',$strAgent)){
					$os = 'Windows 8';
				} else if(@eregi('win',$strAgent) && @eregi('nt 6.1',$strAgent)){
					$os = 'Windows 7';
				} else if(@eregi('win',$strAgent) && @eregi('nt 6.0',$strAgent)){
					$os = 'Windows Vista';
				} else if(@eregi('win',$strAgent) && @eregi('nt 5.2',$strAgent)){
					$os = 'Windows 2003 Server';
				} else if(@eregi('win',$strAgent) && @eregi('nt 5.1',$strAgent)){
					$os = 'Windows XP';
				} else if(@eregi('win',$strAgent) && @eregi('nt 5',$strAgent)){
					$os = 'Windows 2000';
				} else if(@eregi('win',$strAgent) && @eregi('nt',$strAgent)){
					$os = 'Windows NT';
				} else if(@eregi('win',$strAgent) && @eregi('32',$strAgent)){
					$os = 'Windows 32';
				} else if(@eregi('linux',$strAgent)){
					$os = 'Linux';
				} else if(@eregi('unix',$strAgent)){
					$os = 'Unix';
				} else if(@eregi('sun',$strAgent) && @eregi('os',$strAgent)){
					$os = 'SunOS';
				} else if(@eregi('ibm',$strAgent) && @eregi('os',$strAgent)){
					$os = 'IBM OS/2';
				} else if(@eregi('mac',$strAgent) && @eregi('pc',$strAgent)){
					$os = 'Macintosh';
				} else if(@eregi('powerpc',$strAgent)){
					$os = 'PowerPC';
				} else if(@eregi('aix',$strAgent)){
					$os = 'AIX';
				} else if(@eregi('HPUX',$strAgent)){
					$os = 'HPUX';
				} else if(@eregi('netbsd',$strAgent)){
					$os = 'NetBSD';
				} else if(@eregi('bsd',$strAgent)){
					$os = 'BSD';
				} else if(@eregi('OSF1',$strAgent)){
					$os = 'OSF1';
				} else if(@eregi('IRIX',$strAgent)){
					$os = 'IRIX';
				} else if(@eregi('FreeBSD',$strAgent)){
					$os = 'FreeBSD';
				} else if(@eregi('teleport',$strAgent)){
					$os = 'teleport';
				} else if(@eregi('flashget',$strAgent)){
					$os = 'flashget';
				} else if(@eregi('webzip',$strAgent)){
					$os = 'webzip';
				} else if(@eregi('offline',$strAgent)){
					$os = 'offline';
				} else{
					$os = 'Unknown OS';
				}
				return $os;
				}

			
		//数组转换成json
		public function array_to_json($array){
			if( !is_array( $array ) ){
				return false;
			}
		
			$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
			if( $associative ){
		
				$construct = array();
				foreach( $array as $key => $value ){
		
					// We first copy each key/value pair into a staging array,
					// formatting each key and value properly as we go.
		
					// Format the key:
					if( is_numeric($key) ){
						$key = "key_$key";
					}
					$key = "'".addslashes($key)."'";
		
					// Format the value:
					if( is_array( $value )){
						$value = array_to_json( $value );
					} else if( !is_numeric( $value ) || is_string( $value ) ){
						$value = "'".addslashes($value)."'";
					}
		
					// Add to staging array:
					$construct[] = "$key: $value";
				}
		
				// Then we collapse the staging array into the JSON form:
				$result = "{ " . implode( ", ", $construct ) . " }";
		
			} else { // If the array is a vector (not associative):
		
				$construct = array();
				foreach( $array as $value ){
		
					// Format the value:
					if( is_array( $value )){
						$value = array_to_json( $value );
					} else if( !is_numeric( $value ) || is_string( $value ) ){
						$value = "'".addslashes($value)."'";
					}
		
					// Add to staging array:
					$construct[] = $value;
				}
		
				// Then we collapse the staging array into the JSON form:
				$result = "[ " . implode( ", ", $construct ) . " ]";
			}
		
			return $result;
		}
		
		//发送电子邮件
		//参数依次是 邮箱配置参数/发送给谁/接收人的称谓/来自/主题 /内容/邮箱配置
		public function send_email($email_config,$sendemail="",$sendname="",$formname="",$subject="",$content=""){
			$re=array("status"=>"false","Description"=>"Parameter error");
			if(!empty($sendemail)){
				if(strlen($sendemail)>50){
					$re=array("status"=>"error","Description"=>"email error");
				}else if(preg_match("/^([a-zA-Z0-9]+[_|\_|\.|-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.|-]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/",$sendemail)){
					//引用发送邮件类
					require_once(dirname(__FILE__)."/class.email/class.phpmailer.php");
					$mail = new PHPMailer();
		
					$mail->IsSMTP(); // set mailer to use SMTP
					$mail->SMTPAuth = true; // 启用SMTP验证功
					$mail->CharSet=$email_config["charset"];// 设置邮件的字符编 统一为utf-8
					$mail->Host = $email_config["Host"]; // 您的企业邮箱域名
					$mail->Username = $email_config["Username"]; //邮箱用户名(请填写完整的email地址)
					$mail->Password = $email_config["Password"] ; //邮箱密码
					$mail->From = $email_config["From"]; //邮件发送者email地址
					//$mail->AddAddress("ellen@site.com");   // name is optional
					//$mail->AddReplyTo("info@site.com", "Information");
					$mail->WordWrap = $email_config["WordWrap"];   //设置自动换行
					//附件
					//$mail->AddAttachment("附件路径");
					$mail->FromName = $formname;
					$mail->IsHTML(true);    // set email format to HTML
					$mail->AddAddress("$sendemail", "$sendname");//收件人
					$mail->Subject = $subject; //邮件标题 　　
					$mail->Body = $content; //邮件内容
					$mail->AltBody = ""; //附加信息，可以省
					if(!$mail->Send()){
						$re=array("status"=>"error","Description"=>$mail->ErrorInfo);
					}else{
						$re=array("status"=>"true","Description"=>"send success");
					}
				}
		
			}else{
				$re=array("status"=>"error","Description"=>"The mailbox is empty");
			}
			return $re;
		}
		
		//返回提交请求的页面
		public function back_to_which_from($from=1){
			$from = empty($from)?1:$from;
			switch ($from){
				case 1:
					$url = "http://www.193xx.com/";
					break;
				case 2:
					$url = "http://news.193xx.com/";
					break;
				case 3:
					$url = "http://buy.193xx.com/";
					break;
				default:
					$url = "";
					break;
			}
			return $url;
		}
		

}

?>